import {Injectable} from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
    HttpErrorResponse
} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/do';

import {BASEURL} from "../../config/url.config";
import {debarUrl} from "../../config/debar-url.config";
import {STATUS} from "../../config/http-status.config";

import {LoadingService} from "./loading.service";
import {AuthService} from "./auth.service";

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

    constructor(private loadingService: LoadingService) {
    }

    /**
     * 获取请求前缀
     * @param {HttpRequest<any>} req
     * @returns {string}
     */
    getPrefixUrl(req: HttpRequest<any>): string {
        let prefixUrl: string = req.url;

        let x = debarUrl.filter((value) => {
            return req.url.indexOf(value) !== -1;
        });

        if (x.length === 0) {
            prefixUrl = BASEURL + req.url
        }
        return prefixUrl
    }

    /**
     * 请求拦截
     * @param {HttpRequest<any>} req
     * @param {HttpHandler} next
     * @returns {Observable<HttpEvent<any>>}
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        //step.1 处理显示loading提示

        this.loadingService.showLoading(req.url);

        const started: number = Date.now();//请求开始时间

        //step.2 设置请求头

        const authHeader = req.headers.set('Authorization', AuthService.getAuthorizationHeader());

        //step.3 拷贝出新的请求

        const authReq = req.clone({
            headers: authHeader,
            url: this.getPrefixUrl(req)
        });


        return next
            .handle(authReq)
            .do(event => {
                this.successHandle(req, event, started)
            }, (err: HttpErrorResponse) => {
                this.errorHandle(err);
            }, () => {
                this.loadingService.dismissLoading();
            });
    }

    /**
     * 成功回调
     * @param {HttpRequest<any>} req
     * @param event
     * @param {number} started
     */
    successHandle(req: HttpRequest<any>, event, started: number) {
        if (event instanceof HttpResponse) {
            const elapsed = Date.now() - started;
            console.log(`请求 ${req.urlWithParams} 耗时 ${elapsed} ms.`);
        }
    }

    /**
     * 错误回调
     * @param {HttpErrorResponse} err
     */
    errorHandle(err: HttpErrorResponse) {
        this.loadingService.dismissLoading();
        if (err.status === 401) {
            localStorage.clear();
            location.hash = '#/login';
            console.log('登录失效');
        }
        if (err.status === 400) {
            console.log(err);
            if (err.error !== null && err.error.error === "invalid_grant") {
                //todo 后端提示
                let message: string;
                localStorage.getItem('lang') === ('zh') ? message = '账号或密码错误' : message = err.error.error_description;
                this.loadingService.errToast(message);
            }

        }
        if (err.status < 200 || err.status >= 300) {
            // this.loadingService.errToast('网络错误:' + err.status + ' - ' + STATUS['status.' + err.status]);
            console.log('网络错误:' + err.status + ' - ' + STATUS['status.' + err.status]);
        }
    }
}
